from abc import ABC, abstractmethod
import hashlib
import json
from .cart import Cart


class User(ABC):
    """
    用户抽象基类，定义所有用户类型共有的属性和方法
    """
    def __init__(self, user_id, username, password, email, phone):
        self._user_id = user_id
        self._username = username
        self._password = self._hash_password(password)  # 密码加密存储
        self._email = email
        self._phone = phone
        self._is_active = True
    
    def _hash_password(self, password):
        """密码加密方法"""
        return hashlib.sha256(password.encode()).hexdigest()
    
    def verify_password(self, password):
        """验证密码是否正确"""
        return self._password == self._hash_password(password)
    
    @abstractmethod
    def get_user_type(self):
        """获取用户类型"""
        pass
    
    def to_dict(self):
        """将用户信息转换为字典"""
        return {
            'user_id': self._user_id,
            'username': self._username,
            'email': self._email,
            'phone': self._phone,
            'user_type': self.get_user_type(),
            'is_active': self._is_active
        }
    
    # Getter方法
    @property
    def user_id(self):
        return self._user_id
    
    @property
    def username(self):
        return self._username
    
    @property
    def email(self):
        return self._email
    
    @property
    def phone(self):
        return self._phone
    
    @property
    def is_active(self):
        return self._is_active
    
    # Setter方法
    @username.setter
    def username(self, value):
        self._username = value
    
    @email.setter
    def email(self, value):
        self._email = value
    
    @phone.setter
    def phone(self, value):
        self._phone = value
    
    @is_active.setter
    def is_active(self, value):
        self._is_active = value


class Customer(User):
    """
    顾客类，继承自User
    """
    def __init__(self, user_id, username, password, email, phone, address=None):
        super().__init__(user_id, username, password, email, phone)
        self._address = address or []
        self._orders = []  # 订单列表
        self._shopping_cart = Cart()  # 使用Cart类管理购物车
        self._wishlist = []  # 愿望清单
    
    def get_user_type(self):
        return "Customer"
    
    def add_address(self, address):
        """添加收货地址"""
        self._address.append(address)
    
    def add_to_cart(self, product, quantity=1):
        """添加商品到购物车"""
        # 适配新的 add_item 接口
        self._shopping_cart.add_item(
            product.product_id if hasattr(product, 'product_id') else product.id,
            product.name,
            product.price if hasattr(product, 'price') else product.prize,
            quantity
        )
    
    def remove_from_cart(self, product_id):
        """从购物车移除商品"""
        self._shopping_cart.remove_item(product_id)
    
    def update_cart_quantity(self, product_id, quantity):
        """更新购物车商品数量"""
        self._shopping_cart.update_quantity(product_id, quantity)
    
    def add_to_wishlist(self, product):
        """添加商品到愿望清单"""
        if product.product_id not in [p.product_id for p in self._wishlist]:
            self._wishlist.append(product)
    
    def remove_from_wishlist(self, product_id):
        """从愿望清单移除商品"""
        self._wishlist = [p for p in self._wishlist if p.product_id != product_id]
    
    def add_order(self, order):
        """添加订单"""
        self._orders.append(order)
    
    def to_dict(self):
        """将顾客信息转换为字典"""
        base_dict = super().to_dict()
        base_dict.update({
            'address': self._address,
            'order_count': len(self._orders),
            'cart_count': len(self._shopping_cart.items),
            'wishlist_count': len(self._wishlist)
        })
        return base_dict
    
    # Getter方法
    @property
    def address(self):
        return self._address
    
    @property
    def shopping_cart(self):
        return self._shopping_cart
    
    def get_cart_total(self):
        """获取购物车总价"""
        return self._shopping_cart.calculate_total()
    
    @property
    def wishlist(self):
        return self._wishlist
    
    @property
    def orders(self):
        return self._orders


class Seller(User):
    """
    卖家类，继承自User
    """
    def __init__(self, user_id, username, password, email, phone, shop_name, description=None):
        super().__init__(user_id, username, password, email, phone)
        self._shop_name = shop_name
        self._description = description or ""
        self._products = []  # 卖家的商品列表
        self._sales = 0  # 销售额
        self._rating = 0  # 卖家评分
    
    def get_user_type(self):
        return "Seller"
    
    def add_product(self, product):
        """添加商品"""
        self._products.append(product)
    
    def remove_product(self, product_id):
        """移除商品"""
        self._products = [p for p in self._products if p.product_id != product_id]
    
    def update_sales(self, amount):
        """更新销售额"""
        self._sales += amount
    
    def update_rating(self, new_rating):
        """更新评分"""
        # 简单实现，实际可以考虑加权平均
        if len(self._products) > 0:
            self._rating = ((self._rating * (len(self._products) - 1)) + new_rating) / len(self._products)
        else:
            self._rating = new_rating
    
    def to_dict(self):
        """将卖家信息转换为字典"""
        base_dict = super().to_dict()
        base_dict.update({
            'shop_name': self._shop_name,
            'description': self._description,
            'product_count': len(self._products),
            'sales': self._sales,
            'rating': round(self._rating, 2)
        })
        return base_dict
    
    # Getter和Setter方法
    @property
    def shop_name(self):
        return self._shop_name
    
    @shop_name.setter
    def shop_name(self, value):
        self._shop_name = value
    
    @property
    def description(self):
        return self._description
    
    @description.setter
    def description(self, value):
        self._description = value
    
    @property
    def products(self):
        return self._products
    
    @property
    def sales(self):
        return self._sales
    
    @property
    def rating(self):
        return self._rating


class Admin(User):
    """
    管理员类，继承自User
    """
    def __init__(self, user_id, username, password, email, phone, role="Admin"):
        super().__init__(user_id, username, password, email, phone)
        self._role = role
    
    def get_user_type(self):
        return "Admin"
    
    def suspend_user(self, user):
        """暂停用户账户"""
        user.is_active = False
    
    def activate_user(self, user):
        """激活用户账户"""
        user.is_active = True
    
    def remove_product(self, product, product_manager):
        """移除商品"""
        product_manager.remove_product(product.product_id)
    
    def to_dict(self):
        """将管理员信息转换为字典"""
        base_dict = super().to_dict()
        base_dict.update({
            'role': self._role
        })
        return base_dict
    
    @property
    def role(self):
        return self._role


class UserManager:
    """
    用户管理器类，负责用户的创建、查找、验证等功能
    """
    def __init__(self, data_file="users.json"):
        self._users = {}
        self._data_file = data_file
        self._load_users()
    
    def _load_users(self):
        """从文件加载用户数据"""
        try:
            with open(self._data_file, 'r', encoding='utf-8') as f:
                users_data = json.load(f)
                # 检查数据是否为空
                if not users_data:
                    return
                
                for user_data in users_data:
                    try:
                        # 创建用户数据的副本以避免修改原始数据
                        user_data_copy = user_data.copy()
                        
                        # 根据用户类型重新创建用户对象
                        user_type = user_data_copy.pop('user_type')
                        user = None
                        
                        # 移除is_active参数，因为它在User基类中有默认值
                        if 'is_active' in user_data_copy:
                            is_active = user_data_copy.pop('is_active')
                        else:
                            is_active = True
                        
                        # 创建用户对象
                        if user_type == "Customer":
                            user = Customer(**user_data_copy)
                        elif user_type == "Seller":
                            user = Seller(**user_data_copy)
                        elif user_type == "Admin":
                            user = Admin(**user_data_copy)
                        
                        # 设置is_active属性
                        if user:
                            user.is_active = is_active
                            self._users[user.user_id] = user
                    except Exception as e:
                        # 如果单个用户数据有问题，跳过该用户
                        print(f"跳过有问题的用户数据: {e}")
        except FileNotFoundError:
            # 文件不存在，初始化为空
            pass
        except json.JSONDecodeError:
            # JSON解析错误，初始化为空
            pass
        except Exception as e:
            # 捕获其他可能的错误
            print(f"加载用户数据时出错: {e}")
            pass
    
    def save_users(self):
        """保存用户数据到文件"""
        users_data = [user.to_dict() for user in self._users.values()]
        with open(self._data_file, 'w', encoding='utf-8') as f:
            json.dump(users_data, f, ensure_ascii=False, indent=2)
    
    def create_user(self, user_type, **kwargs):
        """创建新用户"""
        user_id = f"{user_type[0].lower()}{len(self._users) + 1}"
        user = None
        
        if user_type == "Customer":
            user = Customer(user_id=user_id, **kwargs)
        elif user_type == "Seller":
            user = Seller(user_id=user_id, **kwargs)
        elif user_type == "Admin":
            user = Admin(user_id=user_id, **kwargs)
        
        if user:
            self._users[user.user_id] = user
            self.save_users()
            return user
        return None
    
    def get_user_by_id(self, user_id):
        """通过ID查找用户"""
        return self._users.get(user_id)
    
    def get_user_by_username(self, username):
        """通过用户名查找用户"""
        for user in self._users.values():
            if user.username == username:
                return user
        return None
    
    def authenticate_user(self, username, password):
        """验证用户身份"""
        user = self.get_user_by_username(username)
        if user and user.verify_password(password) and user.is_active:
            return user
        return None
    
    def get_all_users(self):
        """获取所有用户"""
        return list(self._users.values())
    
    def get_users_by_type(self, user_type):
        """根据用户类型获取用户列表"""
        return [user for user in self._users.values() if user.get_user_type() == user_type]
    
    def update_user(self, user_id, **kwargs):
        """更新用户信息"""
        user = self.get_user_by_id(user_id)
        if not user:
            return False
        
        # 更新用户信息
        for key, value in kwargs.items():
            if hasattr(user, key):
                setattr(user, key, value)
        
        self.save_users()
        return True
    
    def delete_user(self, user_id):
        """删除用户"""
        if user_id in self._users:
            del self._users[user_id]
            self.save_users()
            return True
        return False